<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
  <el-form-item label="订单编号" prop="orderNo">
    <el-input
      v-model="queryParams.orderNo"
      placeholder="请输入订单编号"
      clearable
      @keyup.enter="handleQuery"
    />
  </el-form-item>
  <el-form-item label="老人姓名" prop="elderlyName">
    <el-input
      v-model="queryParams.elderlyName"
      placeholder="请输入老人姓名"
      clearable
      @keyup.enter="handleQuery"
    />
  </el-form-item>
  <el-form-item label="下单人" prop="orderUserName">
    <el-input
      v-model="queryParams.orderUserName"
      placeholder="请输入下单人姓名"
      clearable
      @keyup.enter="handleQuery"
    />
  </el-form-item>
  <el-form-item label="创建时间" style="width: 308px">
    <el-date-picker
      v-model="daterangeCreateTime"
      value-format="YYYY-MM-DD"
      type="daterange"
      range-separator="-"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
    ></el-date-picker>
  </el-form-item>
  <el-form-item style="margin-left: 10px;">
    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
  </el-form-item>
</el-form>
  <!-- 交易状态按钮 -->
   <div class="status-buttons">
    <!-- 全部按钮（值为''，对应默认状态） -->
    <div 
      class="status-btn" 
      :class="{ active: selectedStatus === '' }"
      @click="handleClick('')"
    >
      全部
    </div>
    <!-- 循环渲染订单状态按钮 -->
    <div 
      class="status-btn"
      v-for="dict in order_status" 
      :key="dict.value"
      :class="{ active: selectedStatus === dict.value }"
      @click="handleClick(dict.value)"
    >
      {{ dict.label }}
    </div>
  </div>
    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['orderManagement:orderManagement:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['orderManagement:orderManagement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['orderManagement:orderManagement:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['orderManagement:orderManagement:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table v-loading="loading" :data="orderManagementList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center"><template #default="scope">
        {{ scope.$index + 1 }}
      </template></el-table-column>
      <el-table-column label="订单编号" align="center" prop="orderNo" width="150"/>
      <el-table-column label="老人姓名" align="center" prop="elderly.name" />
      <el-table-column label="床位" align="center" prop="bed.bedNo" />
      <el-table-column label="护理项目名称" align="center" prop="nursingItem.name" width="120" />
      <el-table-column label="订单金额" align="center" prop="orderAmount" />
      <el-table-column label="期望服务时间" align="center" prop="expectedServiceTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expectedServiceTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单人" align="center" prop="orderUser.nickName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="交易状态" align="center" prop="transactionStatus">
        <template #default="scope">
          <dict-tag :options="transaction_status" :value="scope.row.transactionStatus"/>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="140">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleCancel(scope.row)" :disabled="scope.row.orderStatus !== 0">
          取消
        </el-button>
        <el-button link type="primary" size="small" @click="handleRefund(scope.row)" :disabled="![1, 2].includes(scope.row.orderStatus)">退款</el-button>
        <el-button link type="primary" size="small" @click="handleView(scope.row)">
          查看
        </el-button>
      </template>
    </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body align-center>
        <el-form ref="orderManagementRef" :model="title === '填写取消原因' ? form : refundForm" :rules="rules" label-width="80px">
          <el-form-item label="取消原因" prop="cancelReason" v-if="title === '填写取消原因'">
          <el-select v-model="form.cancelReason" placeholder="请选择取消原因">
            <el-option label="不需要此项服务了" value="不需要此项服务了" />
            <el-option label="费用有点贵" value="费用有点贵" />
            <el-option label="临时有事，不方便服务" value="临时有事，不方便服务" />
            <el-option label="信息填写错误" value="信息填写错误" />
            <el-option label="重复下单" value="重复下单" />
          </el-select>
        </el-form-item>
        <el-form-item label="退款原因" prop="refundReason" v-if="title === '填写退款原因'">
          <el-input v-model="refundForm.refundReason" type="textarea" />
        </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
  </div>
</template>

<script setup name="OrderManagement">
import { listOrderManagement, getOrderManagement, delOrderManagement, addOrderManagement, updateOrderManagement } from "@/api/orderManagement/orderManagement"

const { proxy } = getCurrentInstance()
const { order_status, transaction_status } = proxy.useDict('order_status', 'transaction_status')
// 引入编号生成js
import { numberGeneration } from "@/utils/numberGeneration"
import { formatDate } from "@/utils/index"
// 引入退款接口
import { addRefund } from "@/api/orderManagement/refund"

const orderManagementList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeCreateTime = ref([])
// 记录当前选中的状态（默认选中“全部”，对应值''）
const selectedStatus = ref('');

// 点击按钮触发的函数（接收传递的值）
const handleClick = (value) => {
  // 更新选中状态
  selectedStatus.value = value;
  // 执行后续逻辑（如查询、筛选等）
  queryParams.value.orderStatus = value
  console.log('当前选中的值：', value);
  // 可在这里调用接口或其他业务函数
  getList()
};
import { useRouter } from "vue-router";
const router = useRouter();
const handleView=(row)=>{
  console.log(row);
  
  router.push({
    path: `/orderManagement/orderDetailsPage`, // 路径与路由配置的orderDetailsPage匹配，且包含动态参数id
    // 若需要额外参数，可继续用query（不影响路径匹配）
    query: {
      orderId: row.id
    }
  
  });
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    elderlyName: null,      // 改为老人姓名
    orderUserName: null,    // 改为下单人姓名
    createTime: null,
    orderStatus: null,
  },
  rules: {
    cancelReason: [
      { required: true, message: '请选择取消原因', trigger: 'blur' }
    ],
    refundReason: [
      { required: true, message: '请输入退款原因', trigger: 'blur' }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询订单管理列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0]
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1]
  }
  listOrderManagement(queryParams.value).then(response => {
    orderManagementList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  // 1. 重置「取消订单」模型（form）：恢复初始空状态，与定义时字段一致
  form.value = {
    id: null,                  // 订单ID（取消时传递）
    orderNo: null,             // 订单编号（冗余字段，初始空）
    elderlyId: null,           // 老人ID（冗余字段，初始空）
    nursingItemId: null,       // 护理项目ID（冗余字段，初始空）
    orderAmount: null,         // 订单金额（冗余字段，初始空）
    expectedServiceTime: null, // 期望服务时间（冗余字段，初始空）
    orderUserId: null,         // 下单人ID（冗余字段，初始空）
    createTime: null,          // 创建时间（冗余字段，初始空）
    updateTime: null,          // 更新时间（冗余字段，初始空）
    remark: null,              // 备注（冗余字段，初始空）
    orderStatus: null,         // 订单状态（取消时会设为5，初始空）
    transactionStatus: null,   // 交易状态（冗余字段，初始空）
    cancelReason: null,        // 取消原因（核心字段，必须清空）
    isDeleted: null,           // 删除标记（冗余字段，初始空）
    extraField1: null,         // 扩展字段1（冗余字段，初始空）
    extraField2: null          // 扩展字段2（冗余字段，初始空）
  };

  // 2. 重置「退款订单」模型（refundForm）：清空所有退款相关字段
  refundForm.value = {
    refundNo: null,            // 退款编号（前端生成，必须清空）
    orderNo: null,             // 关联订单编号（退款时传递，初始空）
    refundAmount: null,        // 退款金额（订单金额同步，初始空）
    applicant: null,           // 申请人ID（下单人ID同步，初始空）
    applicationTime: null,     // 申请时间（当前时间，初始空）
    refundTime: null,          // 退款时间（后端返回，初始空）
    orderStatus: null,         // 订单状态（退款时设为4，初始空）
    refundStatus: null,        // 退款状态（退款时设为0，初始空）
    refundReason: null         // 退款原因（核心字段，必须清空）
  };

  // 3. 重置表单校验状态：清除之前的错误提示（如未填原因的红色提示）
  // 注意：需确保 "orderManagementRef" 与 el-form 的 ref 属性值一致
  if (proxy.$refs["orderManagementRef"]) {
    proxy.$refs["orderManagementRef"].resetFields();
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 取消操作 */
function handleCancel(row) {
  open.value = true
  title.value = "填写取消原因"
  form.value = {
    id: row.id,
  }
  console.log(form.value);
  
}

/** 退款操作 */
function handleRefund(row) {
    open.value = true
    title.value = "填写退款原因"
    refundForm.value.orderId = row.id
    refundForm.value.refundNo = numberGeneration("TK")
    refundForm.value.orderNo = row.orderNo
    refundForm.value.refundAmount = row.orderAmount
    refundForm.value.applicant = row.orderUser.userId
    refundForm.value.applicationTime = formatDate(new Date())
    refundForm.value.refundTime = formatDate(new Date())
    //改为订单状态为已退款
    refundForm.value.orderStatus = 4
    //改为退款状态为退款成功
    refundForm.value.refundStatus = 0
    console.log(row);
    
    console.log(refundForm.value);  
}
//退款表
const refundForm = ref({
  orderId:null,
  refundNo:null,
  orderNo:null,
  refundAmount:null,
  //申请人id
  applicant:null,
  applicationTime:null,
  refundTime:null,
  orderStatus:null,
  //退款状态
  refundStatus:null,
  //退款原因
  refundReason:null,

})


function submitForm() {
  if (title.value === "填写取消原因") {
    // 取消场景：原有验证逻辑不变
    proxy.$refs["orderManagementRef"].validate(valid => {
      if (valid) {
        form.value.orderStatus = 5;
        form.value.transactionStatus = 2;
        updateOrderManagement(form.value).then(response => {
          proxy.$modal.msgSuccess("取消成功");
          open.value = false;
          getList();
        });
      }
    });
  } else if (title.value === "填写退款原因") {
    // 退款场景：后端会自动处理订单状态更新和余额更新
    proxy.$refs["orderManagementRef"].validate(valid => {
      if (valid) {
        // 添加退款记录（后端会自动更新订单状态和老人余额）
        addRefund(refundForm.value).then(response => {
          proxy.$modal.msgSuccess("退款成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error('退款操作失败：', error);
          proxy.$modal.msgError("退款操作失败");
        });
      }
    });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除订单管理编号为"' + _ids + '"的数据项？').then(function() {
    return delOrderManagement(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('orderManagement/orderManagement/export', {
    ...queryParams.value
  }, `orderManagement_${new Date().getTime()}.xlsx`)
}


getList()
</script>

<style scoped>
  .status-buttons {
  display: flex;  /* 横向排列 */
  gap: 12px;      /* 按钮之间的间距 */
  padding: 5px 5px;
  background-color: #F2F2F2;
  margin-top: 5px;
  margin-bottom: 5px;
  width: 590px;
}

.status-btn {
  /* 基础样式 */
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: black;  /* 未选中文字颜色 */
  transition: all 0.2s;  /* 过渡动画 */
}

/* 选中样式（通过active类控制） */
.status-btn.active {
  background: white;  /* 选中背景色（自定义） */
  color: black;          /* 选中文字颜色 */
  /* 可选：添加阴影增强选中效果 */
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

/* 鼠标悬停样式 */
.status-btn:not(.active):hover {
  background: #e9e9e9;  /* 未选中时的悬停背景 */
}
</style>
